package com.firmboy.mysql.db;

import java.io.BufferedReader;
import java.io.FileReader;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * 加载配置文件的一个公共类
 *
 * @author firmboy
 * @create 2018-04-15 下午7:31
 **/
public class DBResource {

    private String url;

    private String userName;

    private String passWord;

    private String driverClass;

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassWord() {
        return passWord;
    }

    public void setPassWord(String passWord) {
        this.passWord = passWord;
    }

    public String getDriverClass() {
        return driverClass;
    }

    public void setDriverClass(String driverClass) {
        this.driverClass = driverClass;
    }


    /**
     * 静态方法，通过设置四大参数获取到resource
     * @param url
     * @param userName
     * @param passWord
     * @param driverClass
     * @return
     */
    public static DBResource getResource(String url, String userName, String passWord, String driverClass){
        DBResource resource = new DBResource();

        resource.setUrl(url);
        resource.setUserName(userName);
        resource.setPassWord(passWord);
        resource.setDriverClass(driverClass);

        return resource;
    }


    public static DBResource getResource(String path){
        DBResource dbResource= new DBResource();

        URL resource = DBResource.class.getResource("/");
        String rootath = resource.getPath();
        int target = rootath.lastIndexOf("target");
        rootath = rootath.substring(0, target);
        rootath=rootath+"src/main/java/"+path;
        Map<String, String> map = new HashMap<>();
        try {
            FileReader fileReader = new FileReader(rootath);
            BufferedReader bf = new BufferedReader(fileReader);
            String s = "";
            while((s = bf.readLine())!=null){
                String[] split = s.split("=");
                map.put(split[0],split[1]);
            }
            dbResource.setUrl(map.get("url"));
            dbResource.setUserName(map.get("userName"));
            dbResource.setPassWord(map.get("passWord"));
            dbResource.setDriverClass(map.get("DriverClass"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dbResource;
    }

}
